import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AnyCourse } from './entities/any.course.entity';
import { AnyStudent } from './entities/any.student.entity';
import { Repository } from 'typeorm';

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(AnyCourse)
    private coursesRepository: Repository<AnyCourse>,
    @InjectRepository(AnyStudent)
    private studentsRepository: Repository<AnyStudent>,
  ) {}

  async addCourseToStudent(studentId: number, courseId: number): Promise<any> {
    const student = await this.studentsRepository.findOne({ where: { id: studentId }, relations: ['courses'] });
    const course = await this.coursesRepository.findOne({ where: { id: courseId }, relations: ['students'] });
    if (!student || !course) {
      throw new BadRequestException('找不到学生或课程');
    }
    console.log('student',student)
    console.log('course',course)  
    student.courses.push(course);
    await this.studentsRepository.save(student);
    return {
      status: 200,
      message: '向学生添加课程成功',
    };
  }
}
